import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import {
  LoginService,
  GetUserListService,
  GetUserSearchService,
  GetUserByIdService,
  GetMenuService,
  GetDepartmentService,
} from "@/service";
import { SocketServer } from "@/App";
export interface InitialPost {
  user_name: string;
  password: string;
}
export const fetchUserLoginThunk = createAsyncThunk<any, any>(
  "fetch/userloginthunk",
  async (data, { dispatch }) => {
    const res: any = await LoginService(data);
    console.log("login ", res, data);
    if (res.code == 0) {
      const { token, id } = res.data;
      localStorage.setItem("token", token);
    }
    return res;
  }
);

export const fetchGetUserListThunk = createAsyncThunk(
  "fetch/getuserlistthunk",
  async (_, { dispatch }) => {
    const res = await GetUserListService();
    dispatch(SaveUserListActions(res.data.users));
    return res.data;
  }
);

export const fetchSearchUserListThunk = createAsyncThunk<any, any>(
  "fetch/searchuserlistthunk",
  async (data, { dispatch }) => {
    const res = await GetUserSearchService(data);
    dispatch(SaveUserListActions(res.data.users));
    return res.data;
  }
);

export const fetchMenuThunk = createAsyncThunk<any, any>(
  "fetch/menu",
  async (id, { dispatch }) => {
    const user = await GetUserByIdService(id);
    dispatch(SaveUserDetailActions(user.data));
    console.log("=> ", user);
    localStorage.setItem("user", JSON.stringify(user.data));
    GetMenuService(user.data.permissions).then((res) => {
      const items = res.data.list?.map((item: any) => {
        return {
          label: item.name,
          key: item.name,
          icon: item.icon,
          id: item.ID,
          children: item.children?.map((itemy: any) => ({
            label: itemy.name,
            key: itemy.path,
            id: itemy.ID,
            file: itemy.file,
          })),
        };
      });
      dispatch(
        SaveMenuActions({
          list: items ?? [],
          total: res.data.total,
        })
      );
    });
  }
);
export const fetchUserDetail = createAsyncThunk<any, any>(
  "fetch/menu",
  async (id, { dispatch }) => {
    const user = await GetUserByIdService(id);
    dispatch(SaveUserDetailActions(user.data));
    localStorage.setItem("user", JSON.stringify(user.data));
  }
);
export const fetchDepartmentThunk = createAsyncThunk(
  "fetch/department",
  async (_, { dispatch }) => {
    const res = await GetDepartmentService();
    dispatch(SaveDepartmentActions(res.data));
    return res.data;
  }
);

export interface IinitialState {
  users: any[];
  user: any;
  menu: any[];
  menuTotal: number;
  breadcrumb: any[];
  innerWidth: number;
  activeNames: string[];
  reviewNumber: number;
  department: any[];
}

const initialState: IinitialState = {
  users: [],
  user: null,
  menu: [],
  menuTotal: 0,
  breadcrumb: [],
  innerWidth: 0,
  activeNames: [],
  reviewNumber: 0,
  department: [],
};

const userSlice = createSlice({
  name: "userSlice",
  initialState,
  reducers: {
    SaveUserDetailActions(state, { payload }) {
      state.user = payload;
      localStorage.setItem("user", JSON.stringify(payload));
    },
    SaveUserListActions(state, { payload }) {
      state.users = payload;
    },
    ResetSliceActions(state) {
      localStorage.removeItem("token");
      localStorage.removeItem("user");
      SocketServer?.close()
    },
    SaveMenuActions(state, { payload }) {
      state.menu = payload.list;
      state.menuTotal = payload.total;
    },
    SaveBreadCrumbActions(state, { payload }) {
      state.breadcrumb = payload;
    },
    SaveInnerWidthActions(state, { payload }) {
      state.innerWidth = payload;
    },
    SaveActiveNamesActions(state, { payload }) {
      state.activeNames = payload;
    },
    SaveReviewNumberActions(state, { payload }) {
      state.reviewNumber = payload;
    },
    SaveDepartmentActions(state, { payload }) {
      state.department = payload;
    },
  },
});
export const {
  SaveUserListActions,
  SaveUserDetailActions,
  ResetSliceActions,
  SaveMenuActions,
  SaveBreadCrumbActions,
  SaveInnerWidthActions,
  SaveActiveNamesActions,
  SaveReviewNumberActions,
  SaveDepartmentActions,
} = userSlice.actions;
export default userSlice.reducer;
